﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BuildPlannerLib.Buildings;
using BuildPlannerLib.PlayerActions;
using BuildPlannerLib.SimEvents;
using BuildPlannerLib.Terran.Buildings;
using BuildPlannerLib.Enums;

namespace BuildPlannerLib.Terran.PlayerActions
{
    // Derived class from Action for producing an SCV
    public class ProduceSCV : PlayerAction
    {
        // Field for the Command Center
        public IndividualCommandCenter CommandCenter;

        // Constructor with parameter for build
        public ProduceSCV(Build build)
        {
            Build = build;
            MineralCost = 50;
            SupplyCost = 1;
            TimeDuration = 1700;
            Description = "Produce SCV";
            LongDescription = "Producing a new SCV from a Command Center.";
        }

        // Evaluates whether the player is Terran, whether there is mineral income or enough minerals, and whether there will be supply available
        public override bool RequirementsFilled()
        {
            Error = null;
            if (Build.Race != Race.Terran)
            {
                Error = "This worker can only be trained by Terran players.";
                return false;
            }

            return base.RequirementsFilled();
        }

        // Evaluates if enough minerals are available, there is supply available, and a CC not in-use
        public override bool StartCheck()
        {
            CommandCenter commandCenter = Build.Player.MainBuilding as CommandCenter;

            bool availableCommandCenter = commandCenter.IndividualMainBuildings.Exists(delegate(IndividualMainBuilding i)
            {
                return !i.InUse;
            });
            if (!availableCommandCenter)
                return false;

            return base.StartCheck();
        }

        // Spends the minerals, adds the supply to the total in-use, selects a Command Center that is free and sets the flag InUse, and adds the event for finishing the action
        public override void StartAction()
        {
            CommandCenter commandCenter = Build.Player.MainBuilding as CommandCenter;

            base.StartAction();

            CommandCenter = commandCenter.IndividualMainBuildings.Find(delegate(IndividualMainBuilding i)
            {
                return (!i.InUse);
            }) as IndividualCommandCenter;
            CommandCenter.StartProduction();
        }

        // Unsets the flag InUse for the Command Center, adds the SCV, and starts the SCV working at the target base
        public override void FinishAction()
        {
            base.FinishAction();

            CommandCenter.FinishProduction();
            Build.Map.Bases.ElementAt(CommandCenter.TargetBase).AddMineralWorker(ref Build);
        }
    }
}
